<template>
  <div class="userStyle">
    <!-- 搜索表单 -->
    <el-card class="search-card">
      <el-form :model="formInline" label-width="100px" ref="searchFormRef">
        <el-row :gutter="20">
          <el-col :xs="24">
            <el-button type="success" @click="add">新增等级</el-button>
          </el-col>
        </el-row>
      </el-form>
    </el-card>

    <!-- 表格 -->
    <div class="table-container">
      <el-table :data="tableData" v-loading="tableLoading" style="width: 100%">
        <el-table-column prop="memberLevelName" label="等级名称" />
        <el-table-column label="等级图标" width="140" align="center">
          <template #default="{ row }">
            <el-image
              v-if="row.memberLevelIcon"
              :src="row.memberLevelIcon"
              class="level-icon"
              fit="contain"
            />
          </template>
        </el-table-column>
        <el-table-column label="等级背景" width="140" align="center">
          <template #default="{ row }">
            <el-image
              v-if="row.memberLevelBackground"
              :src="row.memberLevelBackground"
              class="level-icon"
              fit="contain"
            />
          </template>
        </el-table-column>
        <el-table-column prop="growth" label="成长值" />
        <el-table-column prop="memberLevelReason" label="等级说明" />
        <el-table-column prop="memberIds" label="等级权益" />
        <el-table-column label="操作" width="200">
          <template #default="{ row }">
            <button-table type="edit" @click="edit(row)" />
            <el-popconfirm title="确认删除此等级吗？" @confirm="del(row)">
              <template #reference>
                <button-table type="delete" @click.stop="() => {}" />
              </template>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 分页 -->
    <div class="pagination-wrapper">
      <el-pagination
        :current-page="formInline.page"
        :page-size="formInline.pageSize"
        :page-sizes="[10, 20, 50, 100]"
        :total="total"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 新增/编辑弹窗 -->
    <el-dialog
      v-model="addFormDialog"
      :title="userState === 1 ? '新增等级' : '编辑等级'"
      width="600px"
    >
      <el-form :model="addForm" :rules="rules" label-width="120px" ref="formRef">
        <el-row :gutter="20">
          <el-col :xs="24" :lg="12">
            <el-form-item label="等级名称" prop="memberLevelName">
              <el-input
                v-model="addForm.memberLevelName"
                placeholder="请输入等级名称"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col :xs="24" :lg="12">
            <el-form-item label="成长值" prop="growth">
              <el-input-number
                v-model="addForm.growth"
                :min="0"
                controls-position="right"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :xs="24" :lg="12">
            <el-form-item label="等级图标" prop="memberLevelIcon">
              <el-upload
                class="avatar-uploader"
                :action="uploadUrl"
                :show-file-list="false"
                :on-success="handleIconSuccess"
                :before-upload="beforeAvatarUpload"
              >
                <img v-if="addForm.memberLevelIcon" :src="addForm.memberLevelIcon" class="avatar" />
                <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
              </el-upload>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :lg="12">
            <el-form-item label="等级背景" prop="memberLevelBackground">
              <el-upload
                class="avatar-uploader"
                :action="uploadUrl"
                :show-file-list="false"
                :on-success="handleBgSuccess"
                :before-upload="beforeAvatarUpload"
              >
                <img
                  v-if="addForm.memberLevelBackground"
                  :src="addForm.memberLevelBackground"
                  class="avatar"
                />
                <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
              </el-upload>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="等级说明" prop="memberLevelReason">
          <el-input
            v-model="addForm.memberLevelReason"
            type="textarea"
            :rows="4"
            placeholder="请输入等级说明"
          />
        </el-form-item>
        <el-form-item label="等级权益" prop="ids">
          <el-select
            v-model="addForm.ids"
            multiple
            placeholder="请选择等级权益"
            style="width: 100%"
          >
            <el-option
              v-for="item in tagList"
              :key="item.memberId"
              :label="item.memberName"
              :value="item.memberId"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="addFormDialog = false">取消</el-button>
          <el-button type="primary" @click="save">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
  import { ref, reactive, onMounted } from 'vue'
  import { ElMessage, ElMessageBox } from 'element-plus'
  import {
    getMemberlevel,
    addLevel,
    getLevelInfo,
    deleteLevel,
    changeLevel,
    getMembership,
    MemberLevelParams,
    MemberLevelItem,
    MemberEquityParams,
    MemberEquityItem
  } from '@/api/memberApi'

  // 表格数据
  const tableData = ref<MemberLevelItem[]>([])
  const total = ref(0)
  const tableLoading = ref(false)

  // 搜索表单
  const formInline = ref<MemberLevelParams>({
    memberLevelName: '',
    page: 1,
    pageSize: 10
  })

  // 新增/编辑表单
  const addFormDialog = ref(false)
  const userState = ref(1) // 1-新增 2-编辑
  const addForm = ref<MemberLevelItem>({
    memberLevelId: '',
    memberLevelName: '',
    memberLevelDesc: '',
    memberLevelIcon: '',
    memberLevelBackground: '',
    memberLevelReason: '',
    growth: 0,
    ids: [],
    memberIds: []
  })

  // 表单验证规则
  const rules = {
    memberLevelName: [{ required: true, message: '请输入等级名称', trigger: 'blur' }],
    memberLevelIcon: [{ required: true, message: '请上传等级图标', trigger: 'change' }],
    memberLevelBackground: [{ required: true, message: '请上传等级背景', trigger: 'change' }],
    growth: [{ required: true, message: '请输入成长值', trigger: 'blur' }],
    memberLevelReason: [{ required: true, message: '请输入等级说明', trigger: 'blur' }],
    ids: [{ required: true, message: '请选择等级权益', trigger: 'change' }]
  }

  // 上传地址
  const uploadUrl = ref('/api/upload') // 需要替换为实际的上传地址

  // 表单引用
  const formRef = ref()
  const searchFormRef = ref()

  // 权益列表
  const equity = ref<MemberEquityParams>({
    page: 1,
    pageSize: 1000
  })
  const tagList = ref<MemberEquityItem[]>([])

  // 处理分页
  const handleSizeChange = (val: number) => {
    formInline.value.pageSize = val
    getAll()
  }

  const handleCurrentChange = (val: number) => {
    formInline.value.page = val
    getAll()
  }

  // 获取所有数据
  const getAll = async () => {
    tableLoading.value = true
    // 构造符合后端API要求的参数
    const params = {
      memberLevelName: formInline.value.memberLevelName,
      page: formInline.value.page,
      pageSize: formInline.value.pageSize
    }

    try {
      const res = await getMemberlevel(params)
      // 根据后端返回的数据结构进行适配
      console.log(res.code)
      if (res.code === '200') {
        console.log('执行成功了')
        const list = res.data?.list || []
        // 处理数据，将memberIds字符串转换为显示用的字符串
        tableData.value = list.map((item: any) => {
          return {
            ...item,
            memberIds: item.memberIds || (item.ids ? item.ids.join(',') : '') || ''
          }
        })
        total.value = res.data?.total || 0
      } else {
        ElMessage({
          message: res.message || '数据获取失败',
          type: 'error'
        })
        tableData.value = []
        total.value = 0
      }
    } catch (err) {
      console.error('获取会员等级列表失败:', err)
      ElMessage({
        message: '数据获取失败，请稍后重试',
        type: 'error'
      })
      tableData.value = []
      total.value = 0
    } finally {
      tableLoading.value = false
    }
  }

  // 获取权益列表
  const getTagList = async () => {
    try {
      const res = await getMembership(equity.value)
      console.log(res.code)
      if (res.code === '200') {
        tagList.value = res.data?.list || []
      } else {
        ElMessage({
          message: res.message || '权益列表获取失败',
          type: 'error'
        })
      }
    } catch (err) {
      console.error('获取权益列表失败:', err)
      ElMessage({
        message: '权益列表获取失败，请稍后重试',
        type: 'error'
      })
    }
  }

  // 新增等级
  const add = () => {
    addFormDialog.value = true
    userState.value = 1
    addForm.value = {
      memberLevelId: '',
      memberLevelName: '',
      memberLevelDesc: '',
      memberLevelIcon: '',
      memberLevelBackground: '',
      memberLevelReason: '',
      growth: 0,
      ids: [],
      memberIds: []
    }
  }

  // 编辑等级信息
  const edit = (row: MemberLevelItem) => {
    addFormDialog.value = true
    userState.value = 2
    // 处理编辑时的数据
    const editData: MemberLevelItem = {
      ...row,
      ids: Array.isArray(row.ids)
        ? row.ids
        : ((typeof row.ids === 'string' ? row.ids.split(',') : []) as string[]),
      memberIds: Array.isArray(row.memberIds)
        ? row.memberIds
        : ((typeof row.memberIds === 'string' ? row.memberIds.split(',') : []) as string[])
    }
    addForm.value = editData
  }

  // 删除等级
  const del = async (row: MemberLevelItem) => {
    ElMessageBox.confirm('是否继续删除此等级?', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
      .then(() => {
        deleteLevel({ memberLevelId: row.memberLevelId })
          .then((res: any) => {
            if (res.code === '200') {
              ElMessage({
                type: 'success',
                message: '删除成功!'
              })
              getAll()
            } else {
              ElMessage({
                type: 'error',
                message: res.message || '删除失败'
              })
            }
          })
          .catch((err: any) => {
            console.error('删除失败:', err)
            ElMessage({
              type: 'error',
              message: '删除失败，请稍后重试'
            })
          })
      })
      .catch(() => {
        return false
      })
  }

  // 保存表单
  const save = () => {
    formRef.value.validate((valid: boolean) => {
      if (valid) {
        // 处理表单数据
        const formData = {
          ...addForm.value,
          ids: Array.isArray(addForm.value.ids) ? addForm.value.ids : []
        }

        if (userState.value === 1) {
          // 新增
          addLevel(formData)
            .then((res) => {
              if (res.code === '200') {
                ElMessage({
                  message: '新增成功',
                  type: 'success'
                })
                getAll()
                addFormDialog.value = false
              } else {
                ElMessage({
                  message: res.message || '新增失败',
                  type: 'error'
                })
              }
            })
            .catch((err) => {
              console.error('新增失败:', err)
              ElMessage({
                message: '新增失败，请稍后重试',
                type: 'error'
              })
            })
        } else {
          // 编辑
          changeLevel(formData)
            .then((res) => {
              if (res.code === '200') {
                ElMessage({
                  message: '编辑成功',
                  type: 'success'
                })
                getAll()
                addFormDialog.value = false
              } else {
                ElMessage({
                  message: res.message || '编辑失败',
                  type: 'error'
                })
              }
            })
            .catch((err) => {
              console.error('编辑失败:', err)
              ElMessage({
                message: '编辑失败，请稍后重试',
                type: 'error'
              })
            })
        }
      } else {
        return false
      }
    })
  }

  // 上传图片相关方法
  const handleIconSuccess = (response: any) => {
    // 需要根据实际的上传接口返回结构调整
    if (response.code === '200' && response.data && response.data.url) {
      addForm.value.memberLevelIcon = response.data.url
    } else {
      ElMessage({
        message: response.message || '上传失败',
        type: 'error'
      })
    }
  }

  const handleBgSuccess = (response: any) => {
    // 需要根据实际的上传接口返回结构调整
    if (response.code === '200' && response.data && response.data.url) {
      addForm.value.memberLevelBackground = response.data.url
    } else {
      ElMessage({
        message: response.message || '上传失败',
        type: 'error'
      })
    }
  }

  const beforeAvatarUpload = (rawFile: File) => {
    if (rawFile.type !== 'image/jpeg' && rawFile.type !== 'image/png') {
      ElMessage.error('头像图片只能是 JPG/PNG 格式!')
      return false
    } else if (rawFile.size / 1024 / 1024 > 2) {
      ElMessage.error('头像图片大小不能超过 2MB!')
      return false
    }
    return true
  }

  // 重置
  const reset = () => {
    formInline.value = {
      memberLevelName: '',
      page: 1,
      pageSize: 10
    }
    getAll()
  }

  onMounted(() => {
    getAll()
    getTagList()
  })
</script>

<style lang="scss" scoped>
  .userStyle {
    padding: 20px;
    margin-top: 20px;
    background-color: var(--art-bg-color);
  }

  .search-card {
    margin-bottom: 20px;
  }

  .text-align-right {
    text-align: right;

    @media screen and (max-width: 768px) {
      display: flex;
      flex-wrap: wrap;
      justify-content: flex-start;
      margin-top: 10px;

      .el-button {
        margin-bottom: 10px;
      }
    }
  }

  .level-icon {
    width: 80px;
    height: 80px;
  }

  .dialog-footer {
    text-align: right;
  }

  // 表格容器样式
  .table-container {
    width: 100%;
    overflow-x: auto;
    overflow-y: auto !important;
    margin-bottom: 20px;
    border-radius: 8px;
    box-shadow: 0 1px 6px 0 rgba(0, 0, 0, 0.05);
    background-color: var(--art-main-bg-color);
    -webkit-overflow-scrolling: touch !important;
    touch-action: pan-y !important;
  }

  // 分页容器样式
  .pagination-wrapper {
    box-sizing: border-box;
    overflow-x: auto !important;
    overflow-y: hidden !important;
    -webkit-overflow-scrolling: touch !important;
    overscroll-behavior: contain !important;
    touch-action: pan-x !important;
  }

  :deep(.el-pagination) {
    display: flex !important;
    flex-wrap: nowrap !important;
    align-items: center !important;
    justify-content: flex-start !important;
    width: auto !important;
    margin: 0 !important;
    padding: 20px 0;
  }

  // 调整分页组件元素间距和显示
  :deep(.el-pagination__sizes),
  :deep(.el-pagination__total) {
    margin-right: 10px !important;
    margin-left: 0 !important;
    white-space: nowrap !important;
    flex-shrink: 0 !important;
  }

  :deep(.el-pagination__prev),
  :deep(.el-pagination__next),
  :deep(.el-pagination__number) {
    margin: 0 2px !important;
    padding: 0 8px !important;
  }
</style>

<style>
  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    transition: var(--el-transition-duration-fast);
  }

  .avatar-uploader .el-upload:hover {
    border-color: #409eff;
  }

  .el-icon.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 100px;
    height: 100px;
    text-align: center;
  }

  .avatar {
    width: 100px;
    height: 100px;
    display: block;
  }
</style>
